//databasehandler.cpp
#include <QUuid> // 添加QUuid头文件
#include "databasehandler.h"
#include <QSqlError>
#include <QDebug>
#include <QSqlQuery>
#include <QCryptographicHash>
#include <QFile>

DatabaseHandler::DatabaseHandler(QObject *parent)
    : QObject(parent)
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
}

bool DatabaseHandler::connect()
{
    // 连接SQLite数据库
    qDebug() << "[DatabaseHandler] 正在连接数据库 audit_trail.db";
    m_db.setDatabaseName("audit_trail.db");
    
    if (!m_db.open()) {
        // 连接失败时记录错误
        QString error = m_db.lastError().text();
        qDebug() << "[DatabaseHandler] 数据库连接失败:" << error;
        emit errorOccurred(error);
        return false;
    }
    
    qDebug() << "[DatabaseHandler] 数据库连接成功";
    return true;
}

bool DatabaseHandler::isConnected() const
{
    return m_db.isOpen();
}

QSqlDatabase& DatabaseHandler::database()
{
    return m_db;
}

DatabaseHandler::~DatabaseHandler()
{
    if (m_db.isOpen()) {
        m_db.close();
    }
}

bool DatabaseHandler::userExists(const QString &username) const
{
    // 检查用户名是否已存在
    qDebug() << "[DatabaseHandler] 检查用户名是否存在:" << username;
    
    QSqlQuery query(m_db);
    query.prepare("SELECT COUNT(*) FROM users WHERE username = :username");
    query.bindValue(":username", username);
    
    qDebug() << "[DatabaseHandler] 执行用户存在查询";
    if(!query.exec() || !query.next()) {
        // 查询失败时记录错误
        QString error = query.lastError().text();
        qDebug() << "[DatabaseHandler] 用户存在查询失败:" << error;
        const_cast<DatabaseHandler*>(this)->m_lastError = error;
        return false;
    }
    
    bool exists = query.value(0).toInt() > 0;
    qDebug() << "[DatabaseHandler] 用户存在查询结果:" << exists;
    return exists;
}

bool DatabaseHandler::addUser(const QString &username, const QString &password, const QString &role)
{
    // 添加新用户到数据库
    qDebug() << "[DatabaseHandler] 开始添加用户:" << username << "角色:" << role;
    
    // 首先检查用户是否已存在
    if(userExists(username)) {
        qDebug() << "[DatabaseHandler] 用户已存在:" << username;
        m_lastError = "User already exists";
        return false;
    }

    // 准备插入用户的SQL查询
    QSqlQuery query(m_db);
    query.prepare("INSERT INTO users (id, username, password_hash, full_name, role) "
                 "VALUES (:id, :username, :password_hash, :full_name, :role)");
    
    // 生成UUID作为用户ID
    QUuid uuid = QUuid::createUuid();
    query.bindValue(":id", uuid.toString(QUuid::WithoutBraces));
    query.bindValue(":username", username);
    query.bindValue(":password_hash", hashPassword(password));
    query.bindValue(":full_name", username);
    query.bindValue(":role", role);

    // 调试输出SQL和绑定值
    qDebug() << "[DatabaseHandler] 执行SQL:" << query.lastQuery();
    qDebug() << "[DatabaseHandler] 绑定值:" << query.boundValues();

    // 执行查询
    qDebug() << "[DatabaseHandler] 正在执行用户添加操作";
    if(!query.exec()) {
        // 查询失败时记录错误
        m_lastError = query.lastError().text();
        qDebug() << "[DatabaseHandler] 添加用户失败:" << m_lastError;
        return false;
    }

    qDebug() << "[DatabaseHandler] 用户添加成功:" << username;
    return true;
}

bool DatabaseHandler::deleteUser(const QString &username)
{
    // 删除指定用户
    qDebug() << "[DatabaseHandler] 正在删除用户:" << username;
    
    QSqlQuery query(m_db);
    query.prepare("DELETE FROM users WHERE username = :username");
    query.bindValue(":username", username);
    
    qDebug() << "[DatabaseHandler] 执行用户删除操作";
    if(!query.exec()) {
        // 删除失败时记录错误
        QString error = query.lastError().text();
        qDebug() << "[DatabaseHandler] 删除用户失败:" << error;
        m_lastError = error;
        return false;
    }
    
    bool success = query.numRowsAffected() > 0;
    qDebug() << "[DatabaseHandler] 删除用户结果:" << success;
    return success;
}

QString DatabaseHandler::lastError() const
{
    return m_lastError;
}

QString DatabaseHandler::databasePath() const
{
    return m_dbPath;
}

QString DatabaseHandler::getEncryptionPassword() const
{
    return m_encryptionPassword;
}

bool DatabaseHandler::isEncrypted() const
{
    return m_encrypted;
}

QString DatabaseHandler::hashPassword(const QString &password) const
{
    return QString(QCryptographicHash::hash(
        password.toUtf8(), QCryptographicHash::Sha256).toHex());
}

bool DatabaseHandler::initialize(const QString &dbPath, const QString &password)
{
    // 初始化数据库连接和表结构
    qDebug() << "[DatabaseHandler] 正在初始化数据库:" << dbPath;
    
    m_dbPath = dbPath;
    m_db = QSqlDatabase::addDatabase("QSQLITE", "main_connection");
    m_db.setDatabaseName(m_dbPath);

    // 第一次打开数据库时不设置密码
    qDebug() << "[DatabaseHandler] 尝试打开数据库连接";
    if (!m_db.open()) {
        QString error = m_db.lastError().text();
        qCritical() << "[DatabaseHandler] 打开数据库失败:" << error;
        return false;
    }

    // 检查是否是新建的数据库
    bool isNewDatabase = !m_db.tables().contains("sqlite_master");
    qDebug() << "[DatabaseHandler] 是否为新建数据库:" << isNewDatabase;

    // 应用加密
    if (!password.isEmpty()) {
        qDebug() << "[DatabaseHandler] 正在应用数据库加密";
        if (!applyEncryption(password)) {
            qCritical() << "[DatabaseHandler] 应用数据库加密失败";
            return false;
        }
        m_encryptionPassword = password;
        m_encrypted = true;
        qDebug() << "[DatabaseHandler] 数据库加密成功";
    }

    // 如果是新建的数据库，执行初始化脚本
    if (isNewDatabase) {
        qDebug() << "[DatabaseHandler] 正在执行初始化脚本";
        if (!executeScript(":/sql/audit_schema.sql")) {
            qCritical() << "[DatabaseHandler] 执行初始化脚本失败";
            return false;
        }
        qDebug() << "[DatabaseHandler] 数据库初始化完成";
    } else {
        // 检查并创建缺失的索引
        QStringList requiredIndexes = {
            "idx_audit_timestamp",
            "idx_audit_user", 
            "idx_audit_action",
            "idx_audit_table"
        };
        
        QSqlQuery query(m_db);
        for (const QString &indexName : requiredIndexes) {
            query.prepare("SELECT name FROM sqlite_master WHERE type='index' AND name=?");
            query.addBindValue(indexName);
            
            if (!query.exec() || !query.next()) {
                qWarning() << "[DatabaseHandler] 检查索引" << indexName << "失败:" << query.lastError().text();
                continue;
            }
            
            if (!query.isValid()) {
                qDebug() << "[DatabaseHandler] 创建缺失索引:" << indexName;
                if (!query.exec(QString("CREATE INDEX IF NOT EXISTS %1 ON audit_log(%2)")
                    .arg(indexName)
                    .arg(indexName.mid(11)))) { // 去掉idx_audit_log_前缀
                    qWarning() << "[DatabaseHandler] 创建索引" << indexName << "失败:" << query.lastError().text();
                }
            }
        }
    }

    qDebug() << "[DatabaseHandler] 数据库初始化成功";
    return true;
}

bool DatabaseHandler::executeScript(const QString &scriptPath)
{
    // 执行SQL脚本文件
    qDebug() << "[DatabaseHandler] 正在执行SQL脚本:" << scriptPath;
    
    QFile scriptFile(scriptPath);
    if (!scriptFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCritical() << "[DatabaseHandler] 无法打开脚本文件:" << scriptPath;
        return false;
    }

    // 读取脚本内容
    QString script = scriptFile.readAll();
    scriptFile.close();
    qDebug() << "[DatabaseHandler] 读取到" << script.split(';').size() << "条SQL语句";

    // 分割并执行每条SQL语句
    QStringList statements = script.split(';', Qt::SkipEmptyParts);
    QSqlQuery query(m_db);

    foreach (const QString &statement, statements) {
        QString trimmed = statement.trimmed();
        if (!trimmed.isEmpty()) {
            qDebug() << "[DatabaseHandler] 执行SQL:" << trimmed;
            if (!query.exec(trimmed)) {
                QString error = query.lastError().text();
                qCritical() << "[DatabaseHandler] 执行SQL失败:" << trimmed 
                           << "\n错误:" << error;
                return false;
            }
            qDebug() << "[DatabaseHandler] SQL执行成功";
        }
    }

    qDebug() << "[DatabaseHandler] 所有SQL语句执行完成";
    return true;
}

bool DatabaseHandler::applyEncryption(const QString &password)
{
    // 使用SQLCipher进行加密
    QSqlQuery query(m_db);
    QString pragma = QString("PRAGMA key='%1'").arg(password);
    if (!query.exec(pragma)) {
        qCritical() << "Failed to set encryption key:" << query.lastError().text();
        return false;
    }

    // 验证加密是否成功
    if (!verifyEncryption()) {
        qCritical() << "Failed to verify database encryption";
        return false;
    }

    // 重新打开数据库以应用加密
    m_db.close();
    if (!m_db.open()) {
        qCritical() << "Failed to reopen encrypted database:" << m_db.lastError().text();
        return false;
    }

    // 再次设置加密密钥
    if (!query.exec(pragma)) {
        qCritical() << "Failed to set encryption key after reopen:" << query.lastError().text();
        return false;
    }

    return true;
}

bool DatabaseHandler::verifyEncryption() const
{
    QSqlQuery query(m_db);
    if (!query.exec("SELECT count(*) FROM sqlite_master")) {
        // 如果查询失败，可能是由于错误的加密密钥
        return false;
    }
    return true;
}
